package exp;

import exp.Bmp;
import exp.BmpStructureErrorException;
import utils.BasicJPanel;
import utils.VFlowLayout;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;

public class MirrorJPanel extends BasicJPanel implements ActionListener
{
    private final JLabel imageJLabel;
    private final JLabel grayJLabel;

    private final JCheckBox xJCheckBox;
    private final JCheckBox yJCheckBox;

    public MirrorJPanel()
    {
        super();
        setLayout(new BorderLayout());
                {
            JPanel jPanel=new JPanel();
            add(jPanel);
            jPanel.setLayout(new GridLayout(1,2));
            jPanel.add(imageJLabel=new JLabel());
            jPanel.add(grayJLabel=new JLabel());
        }

        JPanel infoJPanel=new JPanel();
        infoJPanel.setBorder(new TitledBorder("操作"));
        JScrollPane jScrollPane=new JScrollPane(infoJPanel);
        jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        add(jScrollPane,BorderLayout.WEST);
        infoJPanel.setLayout(new VFlowLayout());
        infoJPanel.add(xJCheckBox=new JCheckBox("水平镜像"));
        xJCheckBox.addActionListener(this);
        infoJPanel.add(yJCheckBox=new JCheckBox("垂直镜像"));
        yJCheckBox.addActionListener(this);
    }

    private void update()
    {
        final BufferedImage src=(BufferedImage)((ImageIcon)imageJLabel.getIcon()).getImage();
        final boolean dx=xJCheckBox.isSelected();
        final boolean dy=yJCheckBox.isSelected();
        final BufferedImage dst=new BufferedImage(src.getWidth(),src.getHeight(),BufferedImage.TYPE_INT_RGB);
        for(int i=0;i<src.getHeight();++i)
            for(int j=0;j<src.getWidth();++j)
            {
                int ii=dy?(src.getHeight()-i-1):i;
                int jj=dx?(src.getWidth()-j-1):j;
                dst.setRGB(jj,ii,src.getRGB(j,i));
            }
        grayJLabel.setIcon(new ImageIcon(dst));
    }

    public void update(Path path) throws IOException, BmpStructureErrorException
    {
        final Bmp bmp=new Bmp(path);
        imageJLabel.setIcon(new ImageIcon(bmp.getImage()));
        update();
    }

    public String getButtonName()
    {
        return "第2章选做2：图片镜像";
    }


    public void actionPerformed(ActionEvent e)
    {
        update();
    }
}
